package com.fang.algorithm.leecode;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description TODO
 * @date 2022/1/6 10:05 下午
 **/
public class Test01_LRU {
    public static void main(String[] args) {
        LRUMock cache = new LRUMock(2);
        cache.put(1, 1);
        System.out.println("put:1,1 get:1=" + cache.get(1));
        cache.put(2, 2);
        System.out.println("put:2,2 get:2=" + cache.get(2));
        cache.put(3, 3);
        System.out.println("put:3,3 get:3=" + cache.get(3));
        System.out.println("get:1=" + cache.get(1));
    }
}

class LRUMock {
    private final Map<Integer, Integer> cacheMap;

    public LRUMock(int capacity) {
        cacheMap = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
                return cacheMap.size() > capacity;
            }
        };
    }

    public void put(Integer key, Integer value) {
        cacheMap.put(key, value);
    }

    public Integer get(Integer key) {
        return cacheMap.getOrDefault(key, -1);
    }
}
